package siteflash.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import siteflash.data.SiteFlashPersistenceManage;
import siteflash.helper.Paginator;
import siteflash.model.Game;
import siteflash.model.Paginate;
import siteflash.model.Tag;

public class Tags extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
        
        //Get parameter
		String path = ((HttpServletRequest) req).getRequestURI();
		String alias = path.replaceAll("/tags/", "");
        PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
        //List all tags
        Key k = KeyFactory.createKey(Tag.class.getSimpleName(), alias);
        Tag tag = null;
        try {
        	tag = psm.getObjectById(Tag.class, k);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		System.out.println(tag.getName());
		//Set limit and number page
        int limit = 18;
        String strPage = (String) req.getParameter("page");
        int page = 1;
        if (strPage != null) {
        	page = Integer.parseInt(strPage);
        } else {
        	strPage = "1";
        }
        int start = (page - 1) * limit;
        int end = page * limit;
        
        Cache cache=null;
		String cachename = alias + "_" + strPage;
		ArrayList<Game> games = new ArrayList<Game>();
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
        
        
        if (cache.containsKey(cachename)) {
        	games = (ArrayList<Game>) cache.get(cachename);
        	System.out.println("List Game: cache print " + cachename);
        } else {
	        for (int i = 0; i < tag.getGames().size(); i++ ) {
	        	if (i >= start && i < end) {
		        	String gameAlias = tag.getGames().get(i); 
			        Key key = KeyFactory.createKey(Game.class.getSimpleName(), gameAlias);
			        Game game = null;
			        try {
			        	game = psm.getObjectById(Game.class, key);
			        	games.add(game);
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
	        	}
			}
	        cache.put(cachename, games);
	        System.out.println("List game: Data print " + cachename);
        }
        
        //List all tags
        ArrayList<Tag> tags = (ArrayList<Tag>) General.getTags();
        int total = (int) tag.getGames().size();
        
        //List hot game
        ArrayList<Game> hotGames = (ArrayList<Game>) General.hotGames();
        
        //Paginate
        Paginator paginator = new Paginator();
        paginator.setLimit(limit);
        Paginate paginate = paginator.paginate(page, total);
        
        //List hot game
        req.setAttribute("pageName", "tags/"+alias);
        req.setAttribute("tags", tags);
        req.setAttribute("hotGame", hotGames);
        req.setAttribute("games", games);
        req.setAttribute("paginate", paginate);
        try {
        	req.setAttribute("title", "Tags: " + alias  + " - Y1S Game Online Free, Game Flash Free");
            req.setAttribute("keyword", "y1s, y1s.org, flash games, free flash games, online games, play game, fun, flash games online, tag " + alias);
            req.setAttribute("description", "Y1s.org List all game by " + alias + " tags");
        	
            req.getRequestDispatcher("/pages/homepage.jsp").forward(req, resp);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
}
